package com.abigdreamer.im.client.module.main;

import java.util.List;

import com.abigdreamer.im.client.module.messageProcess.IMessageProcess;
import com.abigdreamer.im.client.module.talk.TalkWindow;
import com.abigdreamer.im.client.module.vo.Cache;
import com.abigdreamer.im.client.module.vo.MsgFriendGroup;
import com.abigdreamer.im.client.module.vo.MsgFriendGroupList;
import com.abigdreamer.im.client.module.vo.MsgTeam;
import com.abigdreamer.im.client.module.vo.MsgTeamList;
import com.abigdreamer.im.client.module.vo.MsgUser;
import com.abigdreamer.im.client.ui.BaseFrame;
import com.abigdreamer.im.client.util.EIMLogger;
import com.abigdreamer.im.message.BaseMessage;
import com.abigdreamer.im.message.FriendGroupMessage;
import com.abigdreamer.swing.app.SwingUtil;
import com.thoughtworks.xstream.XStream;

public class GroupMessageProcess implements IMessageProcess {

	public void processMessage(BaseMessage message) {

		EIMLogger.INFO("开始处理消息...");

		FriendGroupMessage groupMessage = (FriendGroupMessage) message;
		final List<MsgFriendGroup> friendGroups = getFriendGroupList(groupMessage.getFriendGroupXML());
		List<MsgTeam> teams = getTeamList(groupMessage.getTeamXML());
		Cache cache = Cache.getInstance();
		cache.setFriendGroups(friendGroups);
		cache.setTeams(teams);
		final MsgUser ower = cache.getUserByID(message.getDestQQ());

		EIMMainFrame.setFriends(friendGroups);
		EIMMainFrame.setOwer(ower);
		TalkWindow.setOwerUser(ower);

		EIMLogger.INFO("初始化主面板...");

		EIMMainFrame mainframe = EIMMainFrame.getInstance();

		EIMLogger.INFO("初始化主面板结束...");
		mainframe.changTryIcon();
		BaseFrame.leftWindow(mainframe);

		EIMLogger.INFO("主面板启动中...");
		SwingUtil.runApp(mainframe);
		EIMLogger.INFO("运行主面板成功...");
	}

	public List<MsgFriendGroup> getFriendGroupList(String friendGroupXML) {
		XStream xstream = new XStream();
		xstream.alias("FriendGrous", MsgFriendGroupList.class);
		xstream.alias("friendGroup", MsgFriendGroup.class);
		xstream.alias("user", MsgUser.class);
		xstream.addImplicitCollection(MsgFriendGroupList.class, "FriendGroups");
		xstream.addImplicitCollection(MsgFriendGroup.class, "userList");
		return ((MsgFriendGroupList) xstream.fromXML(friendGroupXML)).getFriendGroups();
	}

	public List<MsgTeam> getTeamList(String teamXML) {
		XStream xstream = new XStream();
		xstream.alias("Teams", MsgTeamList.class);
		xstream.alias("team", MsgTeam.class);
		xstream.alias("user", MsgUser.class);
		xstream.addImplicitCollection(MsgTeamList.class, "teams");
		xstream.addImplicitCollection(MsgTeam.class, "userList");
		return ((MsgTeamList) xstream.fromXML(teamXML)).getTeams();
	}
}